import "../../../node_modules/leaflet/dist/leaflet.css";
import React, { useEffect, useRef, useState, useCallback } from "react";
import { Button, Flex, Space } from 'antd';
import L from "leaflet";
import 'leaflet-polylineoffset';
import "leaflet/dist/leaflet.css";
import 'leaflet.animatedmarker/src/AnimatedMarker'
import "leaflet.markercluster";
// import 'leaflet-moving-marker'
// import 'leaflet-control-Button';
import 'leaflet-trackplayer'
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import 'leaflet-polylinedecorator';

// import 'leaflet.markercluster/dist/leaflet.markercluster.css';
import leafGreen from "../../assets/img/leaf-green.png"
// ck.png
import ck from "../../assets/assets/ck.png"
import start from "../../assets/assets/start.png"
import end from "../../assets/assets/end.png"
import shipIconActive from "../../assets/assets/supply/shipIconActive.png"
import './index.scss'
import car from "../../assets/assets/car.png"
const key = "03cd4b8189df52cc8fba3d9fd345f747";

// import addressPoints from './data'

export default function Index() {
  const mapRef = useRef(null);
  const [animatedMarker, setAnimatedMarker] = useState(null);
  const [speedMultiplier, setSpeedMultiplier] = useState(1);
  let speetX = 1 // 默认速度倍数
  useEffect(() => {
    setTimeout(() => {
      intiMap();
    }, 5000);
  }, []);

  const addLayer = (map) => {
    let mapTypes = ["vec_w", "cva_w"]; // 矢量&标记
    let layers = []; //天地图图层
    mapTypes.forEach((item) => {
      let layerUrl = `http://t0.tianditu.gov.cn/DataServer?T=${item}&x={x}&y={y}&l={z}&tk=${key}`;
      let layer = L.tileLayer(layerUrl, {});
      layers.push(layer);
    });
    let layerGroup = L.layerGroup(layers).addTo(map);
  };

  const intiMap = () => {
    // 初始化地图
    const map = L.map("mapDiv", {
      crs: L.CRS.EPSG3857,
      center: [39.916578, 116.403653], // 设置中心点（例如北京）
      zoom: 18, // 设置缩放级别
      minZoom: 2,
      maxZoom: 18, // 最大缩放级别
      attributionControl: true, // 隐藏属性说明控件
      draggable: true, // 允许拖动地图
      keyboard: true, // 允许键盘操作地图
      inertia: true, // 启用��性��动
      scrollWheelZoom: true, // 启用��标滚轮缩放
      zoomControl: true, // 显示缩放控件
      doubleClickZoom: true, // 启用双击缩放
      tap: true, // 启用点击事件
      touchZoom: true, // 启用触摸缩放
    });


    // L.marker([116.411794, 39.9068]).addTo(map) //没有图标的标记
    // L.marker([51.5, -0.09], { icon: '../../assets/img/leaf-green.png' }).addTo(map);
    // 创建标记，并添加到地图上
    // L.marker([39.916578, 116.403653], {
    //   icon: L.icon({
    //     iconUrl: leafGreen, //请求图标图片的URL
    //     iconSize: new L.Point(30, 30), //图标可视区域的大小。
    //     iconAnchor: new L.Point(30, 30) //图标的定位锚点

    //     // iconUrl: marker, tooltipAnchor: [0, -36], iconAnchor: [24, 48]
    //     // iconUrl: '../../assets/img/leaf-green.png',
    //     // iconUrl:'../../assets/img/leaf-green.png',
    //     // iconSize: [38, 100],
    //     // iconAnchor: [22, 94],
    //     // popupAnchor: [-3, -76],
    //     // shadowUrl: 'path/to/the/shadow.png',
    //     // shadowSize: [68, 95],
    //     // shadowAnchor: [22, 94]
    //   })
    // }).addTo(map);
// 走动的图标
    const carIcon = L.icon({
      iconSize: [27, 44],//shipIconActive.png
      iconUrl: new URL(car, import.meta.url).href,
      iconAnchor: [0.5, 1]
    })
    // 起点
    L.marker([34.153748, 108.901978], {
      icon: L.icon({
        iconUrl: new URL(start, import.meta.url).href,
        iconSize: [23, 30]
      })
    }).addTo(map)
    // 终点
    L.marker([43.6510, -79.3820], {
      icon: L.icon({
        iconUrl: new URL(end, import.meta.url).href,
        iconSize: [23, 30]
      })
    }).addTo(map)

    const speedList = [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 3, 2, 2, 1, 1, 1]
    const arr = [
      [34.153748, 108.901978],
      // [22.7843651, 113.49106],
      // [39.550781, 116.367188],
      [37.7749, -122.4194], // 例：San Francisco
      // [40.7128, -74.0060], // 例：New York
      [43.6510, -79.3820] // 例：Toronto
    ]
    // 轨迹路线装饰
    const polyline = L.polyline(arr, {
      weight: 8,
    
      opacity: 0.5,
      smoothFactor: 3, // 平滑度
    }).addTo(map);
    //实时轨迹线
    const realRouteLine = L.polyline([],{
      weight: 8,
      color: '#ff9900',
    })
    // 使用L.polylineDecorator 轨迹方向箭头
    const decorator = L.polylineDecorator(polyline, {
      patterns: [
        {
          offset: 10,
          repeat: 50,
          // symbol: L.symbol({
          //   pixelSize: 10,
          //   polygon: true,
          //   pathOptions: {
          //     fillColor: 'red',
          //   }
          // })
          symbol: L.Symbol.arrowHead({
            pixelSize: 5,//箭头大小
            headAngle:75,//箭头重复间距
            polygon: false,
            pathOptions: {
              fillColor: '#fff',
              weight: 1,
              stroke: true,
            }

          })
        }
      ]
    }).addTo(map);

    // 动态marker
    var carMarker = L.animatedMarker(polyline.getLatLngs(), {
      speedList: speedList,
      interval: 200, // 默认为100mm
      icon: carIcon,
      playCall: updateRealLine
    }).addTo(map)
    var newLatlngs = [polyline.getLatLngs()[0]]

    // 绘制已行走轨迹线（橙色那条）
    function updateRealLine(latlng) {
      newLatlngs.push(latlng)
      realRouteLine.setLatLngs(newLatlngs)
    }
    setAnimatedMarker(carMarker);
    // setInterval(() => {
      // var marker = L.animatedMarker(arr, {
      //   autoStart: true,
      //   distance: 1000, // 运动轨迹的总距离，单位为像素
      //   interval: 10000, // 每帧之间的时间间隔，单位为毫秒
      //   icon: iconPng,
      //   onEnd: function () {
      //     //移动结束后移除
      //     // map.removeLayer();
      //   }
      // }).addTo(map);
    // }, 2000)

 




    const icon = L.icon({
      iconUrl: new URL(shipIconActive, import.meta.url).href,
      // shadowUrl: iconShadowUrl,
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41],
      shadowAnchor: [12, 41]
    });





// 聚合物没有出现有bug
    // 示例数据：随机生成的多个点
    const markers = [];
    for (let i = 0; i < 1000; i++) {
      const lat = 51.5 + (Math.random() - 0.5) * 0.5;
      const lng = -0.09 + (Math.random() - 0.5) * 0.5;
      markers.push(L.marker([lat, lng]));
    }

    // 创建MarkerClusterGroup并将标记添加到其中
    const markerClusterGroup = L.markerClusterGroup();
    markerClusterGroup.addLayers(markers);
    map.addLayer(markerClusterGroup);






    // 定义轨迹
    // const polyline = L.polyline([
    //   [51.505, -0.09],
    //   [51.510, -0.10],
    //   [51.515, -0.12],
    //   [51.520, -0.13]
    // ], { color: 'blue' }).addTo(map);

    // // // 偏移轨迹以绘制道路中心线（可选）
    // // const offset = L.polylineOffset(polyline, -3, { units: 'meters' });
    // // // L.polyline(offset.latlngs, { color: 'red' }).addTo(map);

    // // 初始化小车位置
    // const carMarker = L.marker([51.505, -0.09], { icon }).addTo(map);
    // setCarPosition(carMarker);

    // // 小车移动逻辑
    // const moveCar = () => {
    //   if (!carMoving) return;

    //   const latLngs = polyline.getLatLngs();
    //   const currentIndex = latLngs.findIndex(coord =>
    //     L.latLng(coord).equals(carMarker.getLatLng())
    //   );

    //   if (currentIndex < latLngs.length - 1) {
    //     const nextLatLng = latLngs[currentIndex + 1];
    //     const currentLatLng = carMarker.getLatLng();
    //     const distance = currentLatLng.distanceTo(nextLatLng);
    //     const speed = 0.001; // 每秒移动的距离（以度为单位）

    //     const timeToMove = distance / speed;
    //     setTimeout(() => {
    //       carMarker.setLatLng(nextLatLng);
    //       setCarPosition(carMarker);
    //       moveCar();
    //     }, timeToMove * 1000);
    //   } else {
    //     setCarMoving(false);
    //   }
    // };

    // // 开始移动小车
    // const startMoving = () => {
    //   setCarMoving(true);
    //   moveCar();
    // };

    // 添加按钮或其他方式触发小车移动
    // const startButton = L.control.Button({
    //   position: 'topright',
    //   title: 'Start Car',
    //   className: 'start-Button',
    //   html: '<i class="fa fa-play"></i>'
    // }).addTo(map);

    // startButton.on('click', () => {
    //   startMoving();
    // });






   

    




    addLayer(map);
  };
  // https://github.com/gisarmory/gisarmory.blog/blob/master/leaflet-RouteAnimate/demo.html
  // 地图实现轨迹回放
  // https://blog.csdn.net/qing12313359/article/details/141901445

  const setRealRouteLine = useCallback((latlng, realRouteLine) => {
    const newLatlngs = [...realRouteLine.getLatLngs(), latlng];
    realRouteLine.setLatLngs(newLatlngs);
  }, []);

  const handleStartClick = () => {
    animatedMarker.start();
  };

  const handlePauseClick = () => {
    animatedMarker.pause();
  };

  const handleStopClick = () => {
    // const realRouteLine = map.getLayer('realRouteLine'); // 假设您已经以某种方式标记或引用了这条线
    // realRouteLine.setLatLngs([]);
    animatedMarker.stop();
  };

  const handleSpeedUpClick = () => {
    setSpeedMultiplier(prev => prev * 2);
    updateSpeed(animatedMarker);
  };

  const handleSpeedDownClick = () => {
    setSpeedMultiplier(prev => Math.max(prev / 2, 0.1)); // 避免速度为0或负数
    updateSpeed(animatedMarker);
  };

  const updateSpeed = useCallback((marker) => {
    // 假设您有一个方法来设置速度，这里可能需要调整以适应您的animatedMarker实现
    // marker.setSpeed(...); // 这不是Leaflet.AnimatedMarker API的一部分，所以需要自定义实现
    // 由于Leaflet.AnimatedMarker不支持直接设置速度，这里我们只能通过重新创建marker来模拟
    // 但这通常不是最佳实践。考虑扩展Leaflet.AnimatedMarker以支持动态速度更改。
    // 这里只是示例，所以实际上不更改速度
  }, []);
  return (
    <>
      {/* <Button type="primary" onClick={() => {
        console.log("00000")
      
      }}>开始动画</Button> */}
      <Space>
        <Button type="primary" onClick={window.handleStartClick}>开始</Button>
        <Button type="primary" onClick={window.handlePauseClick}>暂停</Button>
        <Button type="primary" onClick={window.handleSpeedUpClick}>加速</Button>
        <Button type="primary" onClick={window.handleSpeedDownClick}>减速</Button></Space>
      {/* <Button type="primary"  onClick={handleStopClick}>停止</Button> */}
      <div
        id="mapDiv"
        ref={mapRef}
        style={{ height: "83.6vh", width: "85.6%", position: "absolute" }}
      />
    </>
  );
}